<template>
  <div class="content">
    <!--部门管理-->
    <div class="left-nav">
      <div class="nav-title">
        <span class="nav-text">角色管理</span>
        <el-tooltip content="添加角色">
          <el-icon v-auth="'ADD_ROLE'" color="#FF6B00" @click="addRole()"><plus /></el-icon>
        </el-tooltip>
      </div>
      <div class="search-list" v-for="(item, index) in treeData" :key="index" @click="clickSearch(item)" @mouseover="mouseOver(item)" @mouseleave="mouseLeave(item)">
        <el-button :class="item.id == selectId ? 'search-detail-color' : 'search-detail'" type="text"
          >{{ item.name }}<span :class="item.system ? 'detail-color' : 'local-color'">{{ item.system ? '(系统)' : '(自定义)' }}</span></el-button
        >
        <el-tooltip placement="right" effect="light" v-if="item.system == 0">
          <template #content>
            <el-link v-auth="'EDIT_ROLE'" class="link-text" :underline="false" type="primary" @click="editRole(item)">编辑角色</el-link>
          </template>
          <el-icon color="#FF6B00" class="hover-icon" v-show="item.showEdit"><more-filled /></el-icon>
        </el-tooltip>
      </div>
    </div>
    <!---中间栏-->
    <div class="right-content">
      <div class="title-btn">
        <div class="title-detail">
          {{ title.name }}({{ title.system ? '系统' : '自定义' }})<span style="font-size: 12px; margin-left: 10px">已选{{ batchAssign.assign_user_ids.length }}人</span>
        </div>
        <div v-show="activeIndex == 1" class="btn-group">
          <el-button v-if="!editSave && title.name != '超级管理员'" v-auth="'EDIT_PERMISSION'" class="edit-role" @click="editJurisdiction">编辑权限</el-button>
          <div v-if="editSave">
            <el-button class="edit-role" @click="save">保存并退出</el-button>
            <el-button class="cancel" @click="cancel">取消</el-button>
          </div>
        </div>
      </div>
      <el-tabs v-model="activeIndex">
        <el-tab-pane label="权限范围" name="1">
          <div class="company-content">
            <div class="company-role">
              <Jurisdiction :echoList="echoList" :editSave="editSave" :tenantList="tenantList" :permission="permission" @handleCompany="handleCompany" @handleSub="handleSub" @handleSelect="handleSelect"></Jurisdiction>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="子账号列表" name="2">
          <div v-show="activeIndex == 2">
            <!-- <Search :formInline="formInline" @searchChange="getsubList"></Search> -->
            <div class="table-search">
              <!-- <el-select v-model="formInline.type" @change="changePage">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select> -->
              <el-button type="primary" v-auth="EDIT_ROLE" @click="batchEdit">批量修改角色</el-button>
            </div>
          </div>
          <Table ref="tableRef" class="table" :selectId="selectId" @handleDetail="handleDetail" @selectAll="selectAll" @sectionChange="sectionChange" @reset="reset" @search="search"></Table>
          <!-- <Table :tableData="tableData" :pagination="pagination" @handleDetail="handleDetail" @sectionChange="sectionChange" @selectAll="selectAll"></Table> -->
        </el-tab-pane>
      </el-tabs>
    </div>
    <!--添加编辑角色弹框-->
    <Dialog :appDialog="addDialog">
      <div class="add-role">
        <div class="role-label">角色名称：</div>
        <div>
          <el-input v-model="roleName" class="department" maxlength="10" show-word-limit placeholder="请输入不超过10字的角色名称"></el-input>
          <span v-if="!isEdit" class="role-tip">提示：添加完成后，在权限范围中编辑</span>
        </div>
      </div>
    </Dialog>
    <!--修改角色弹框（子账号列表）-->
    <Dialog :appDialog="roleDialog">
      <div>
        <div class="change-title" v-show="!isBatch">
          修改账号名称为：<span class="change-title-color">{{ changeName }}</span
          >的角色
        </div>
        <div class="change-title" v-show="isBatch">
          修改账号名称为：<span class="change-title-color">{{ batchName }}</span
          >的角色
        </div>
        选择角色
        <el-select clearable v-model="role.role_id" placeholder="请选择" class="form-label">
          <el-option v-for="item in roleLists" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </div>
    </Dialog>
    <!--保存权限弹框-->
    <Dialog :appDialog="appDialog">
      <div>
        <div class="tip-title"> 您确认要修改您的权限吗？保存后，该角色下所有子账号都将应用该权限。 </div>
        <div class="save-detail">
          <el-checkbox v-if="account_type == 1" v-model="is_sync_company" @change="changeCheck">同步到其他企业</el-checkbox>
          <el-select v-model="sync_id" v-show="is_sync_company" class="save-select">
            <el-option v-for="item in corpsDetail.value" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </div>
        <div v-show="is_sync_company">
          <div class="tips"> 开启后，其他公司该角色也将应用新的权限，同时，应用该角色的账号权限也会更新。 </div>
          <span class="message">短信验证：</span>
          <div class="save-text">
            超级管理员： {{ userinfophone }}
            <span v-show="sendAuthCode" class="save-link" @click="getCode">获取验证码</span>
            <span v-show="!sendAuthCode" class="save-link">{{ autoTime }}后重新获取</span>
          </div>
          <div class="save-message">
            <div>短信验证码：</div>
            <el-input v-model="verifyCodes" @input="getVerifyCode" maxlength="6" class="save-input"></el-input>
            <div v-if="is_show == 2" class="icon-detail">
              <el-icon class="icon" color="#52c41a"><circle-check-filled /></el-icon>
              <span class="icon-span">验证成功</span>
            </div>
            <div v-if="is_show == 3" class="icon-detail">
              <el-icon class="icon" color="#f5222d"><warning-filled /></el-icon>
              <span class="icon-span">验证失败</span>
            </div>
          </div>
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script lang="ts" setup>
  import Jurisdiction from './components/Jurisdiction.vue'
  import Table from './components/Table.vue'
  import Search from './components/Search.vue'
  import Dialog from '@/components/Dialog.vue'
  import { roleList, roleAdd, roleEdit, roleTenant, roleTenantExist, assignRole, batchAssignRole, screenRoleList, sendCode, verifyCode, roleFunction, permissionEdit } from '@/api/role'
  import { subAcountList } from '@/api/sub'
  import { computed, ref, reactive, onMounted, watch, nextTick } from 'vue'
  import { UserCorp } from '@/store/modules/type'
  import { useStore } from '@/store'
  import { ElMessage } from 'element-plus'

  //变量
  const store = useStore()
  // const userInfo = computed(() => {

  //   return store.state.user.ownerInfo
  // })
  const userinfophone = localStorage.getItem('owner')
  const tableRef = ref(null)
  const showEdit = ref(false) //是否展示角色编辑
  const treeData = ref([]) //角色管理权限列表
  const isEdit = ref(false) //是否是编辑角色
  const roleLists = ref([]) //用于筛选的角色列表
  const tenantList = ref([]) //商户菜单
  const selectTree = ref([])
  const verifyCodes = ref() //验证码
  const echoList = ref([]) //回显列表
  const is_show = ref(1)
  const corps = store.state.user.corps
  const sync_id = ref(0)
  const isSelectAll = ref(false)
  const isBatch = ref(false) //是否是批量操作
  const editSave = ref(false)
  const sendAuthCode = ref(true)
  const autoTime = ref(0)
  const is_sync_company = ref(false) //是否同步到其他企业
  const roleName = ref('')
  const roleId = ref(0)
  const selectId = ref(0)
  const activeIndex = ref('1')
  const changeName = ref('')
  const batchName = ref('')
  const account_type = ref()
  const permission = reactive({
    data_permissions: 1,
    data_premission_type: 1
  })
  const formInline = reactive({
    mobile_or_account_name: '',
    type: 1
  })
  const title = reactive({
    system: 1,
    name: '超级管理员'
  })
  const tableData = ref([])
  const role = reactive({
    role_id: '',
    assign_user_id: ''
  })
  const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })
  const savePermission = reactive({
    data_premission_type: '1', //类型：1-企业 2-集团
    data_permissions: '1', //数据权限 1 全部 2 仅自己 3 自己及部门
    all_menus: '0', //是否全部菜单 1 全部菜单 0 指定菜单
    application_function_id: [], //
    role_id: '', //角色ID
    sys_tenant_corp_id: '' //同步企业ID
  })
  const batchAssign = reactive({
    role_id: '',
    assign_user_ids: [],
    assign_type: 'CURRENT_PAGE' //默认为当前页
  })
  const options = reactive([
    {
      value: 1,
      label: '当前页'
    },
    {
      value: 2,
      label: '所有页'
    }
  ])
  const getDisable = () => {
    if (is_show.value != 2) {
      appDialog.isDisable = true
    } else {
      appDialog.isDisable = false
    }
  }
  //确认保存权限
  const submitHandel = () => {
    savePermission.role_id = selectId.value
    savePermission.sys_tenant_corp_id = sync_id.value
    if (sync_id.value == 0) {
      savePermission.sys_tenant_corp_id = 'OTHER_COMPANY'
    }
    permissionEdit(savePermission).then((data: any) => {
      editSave.value = false
      cancelHandel()
      getRoleList()
    })
  }
  //取消保存权限
  const cancelHandel = () => {
    appDialog.visible = false
  }
  const appDialog = reactive({
    visible: false,
    title: '保存权限',
    width: '500px',
    isDisable: false,
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
  })
  //确认修改角色
  const submitRole = () => {
    if (!role.role_id) {
      ElMessage({
        message: '请选择角色',
        type: 'error'
      })
      return
    }
    roleDialog.visible = false
    if (isBatch.value) {
      batchAssign.role_id = role.role_id
      batchAssignRole(batchAssign).then((data: any) => {
        ElMessage({
          message: '批量修改成功',
          type: 'success'
        })
        tableRef.value.getsubList(selectId.value)
      })
    } else {
      assignRole(role).then((data: any) => {
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        tableRef.value.getsubList(selectId.value)
      })
    }
  }
  //取消修改角色
  const cancelRole = () => {
    roleDialog.visible = false
  }
  const roleDialog = reactive({
    visible: false,
    title: '修改角色',
    width: '500px',
    cancel: cancelRole,
    submit: submitRole,
    cancelText: '取消',
    submitText: '保存'
  })
  //确定添加
  const handleAdd = () => {
    if (!roleName.value) {
      ElMessage({
        message: '请输入角色名称',
        type: 'error'
      })
      return
    }
    if (!isEdit.value) {
      const params = {
        role_name: roleName.value
      }
      roleAdd(params).then((data: any) => {
        addDialog.visible = false
        ElMessage({
          message: '添加成功',
          type: 'success'
        })
        getRoleList()
      })
    } else {
      const params = {
        role_name: roleName.value,
        role_id: roleId.value
      }
      roleEdit(params).then((data: any) => {
        addDialog.visible = false
        ElMessage({
          message: '编辑成功',
          type: 'success'
        })
        getRoleList()
      })
    }
  }
  //取消添加角色
  const cancelAdd = () => {
    addDialog.visible = false
  }
  const addDialog = reactive({
    visible: false,
    title: '添加角色',
    width: '500px',
    cancel: cancelAdd,
    submit: handleAdd,
    cancelText: '取消',
    submitText: '保存'
  })
  //方法
  //获取角色列表
  const getRoleList = () => {
    treeData.value = []
    roleList().then(async (data: any) => {
      treeData.value = data
      title.name = data[0].name
      title.system = data[0].system
      selectId.value = data[0].id
      tableRef.value.getsubList(data[0].id)
      treeData.value.forEach((item: any) => {
        if (item.id == selectId.value) {
          permission.data_permissions = item.data_permissions
          permission.data_premission_type = item.data_premission_type
        }
      })
      await getTenant()
      await getroleFunction()
    })
  }
  getRoleList()
  //获取用于筛选的角色列表
  const getScreenList = () => {
    screenRoleList().then((data: any) => {
      roleLists.value = data
    })
  }
  getScreenList()
  //获取子账号列表
  const getsubList = () => {
    const params = {
      mobile_or_account_name: formInline.mobile_or_account_name
    }
    subAcountList(params).then((data: any) => {
      tableData.value = data.data
    })
  }
  getsubList()
  //获取商户菜单
  const getTenant = () => {
    return roleTenant().then((data: any) => {
      tenantList.value = data
    })
  }
  //获取选中的角色菜单Id
  const getroleFunction = () => {
    const params = {
      role_id: selectId.value
    }
    return roleFunction(params).then((data: any) => {
      echoList.value = data
      savePermission.application_function_id = data
    })
  }
  //添加角色
  const addRole = () => {
    addDialog.visible = true
    addDialog.title = '添加角色'
    roleName.value = ''
    isEdit.value = false
  }
  //点击角色
  const clickSearch = async (data: any) => {
    editSave.value = false
    title.system = data.system
    title.name = data.name
    selectId.value = data.id
    tableRef.value.getsubList(data.id)
    await getTenant()
    await getroleFunction()
    if (data.name == '超级管理员') {
      editSave.value = false
    }
    treeData.value.forEach((item: any) => {
      if (item.id == data.id) {
        permission.data_permissions = item.data_permissions
        permission.data_premission_type = item.data_premission_type
      }
    })
  }
  //编辑角色
  const editRole = (data: any) => {
    addDialog.visible = true
    addDialog.title = '编辑角色'
    isEdit.value = true
    roleName.value = data.name
    roleId.value = data.id
  }
  //编辑权限
  const editJurisdiction = () => {
    // handleSelect()
    editSave.value = true
  }
  //保存权限
  const save = () => {
    appDialog.visible = true
    sendAuthCode.value = true
  }
  //取消权限
  const cancel = () => {
    editSave.value = false
  }
  //修改角色
  const handleDetail = (data: any) => {
    isBatch.value = false
    changeName.value = data.name
    roleDialog.visible = true
    role.assign_user_id = data.id
  }
  const corpsDetail: any = []
  //切换同步其他企业
  const changeCheck = (val: any) => {
    if (val) {
      appDialog.isDisable = true
    } else {
      appDialog.isDisable = false
    }
    corpsDetail.value = JSON.parse(JSON.stringify(corps))
    corpsDetail.value.unshift({
      id: 0,
      name: '其他所有企业'
    })
  }
  //鼠标移入
  const mouseOver = (data: any) => {
    data.showEdit = true
  }
  //鼠标移出
  const mouseLeave = (data: any) => {
    data.showEdit = false
  }
  //获取验证码
  const getCode: () => void = () => {
    sendAuthCode.value = false
    autoTime.value = 60
    let autoTimeTimer = setInterval(() => {
      autoTime.value--
      if (autoTime.value <= 0) {
        sendAuthCode.value = true
        clearInterval(autoTimeTimer)
      }
    }, 1000)
    getCodeList()
  }
  //发送验证码请求
  const getCodeList = () => {
    const params = {
      phone: userinfophone //userInfo.value.phone
    }
    sendCode(params).then((data: any) => {
      ElMessage({
        message: '短信已发送',
        type: 'success'
      })
    })
  }
  //验证验证码
  const getVerifyCode = () => {
    if (verifyCodes.value.length == 6) {
      const params = {
        phone: userinfophone, //userInfo.value.phone,
        verify_code: verifyCodes.value
      }
      verifyCode(params)
        .then((data: any) => {
          if (data.length == 0) {
            is_show.value = 2
            getDisable()
          }
        })
        .catch((data: any) => {
          is_show.value = 3
          getDisable()
        })
    }
  }
  //选中批量修改角色
  const sectionChange = (data: any) => {
    if (data.length > 0) {
      isBatch.value = true
      if (data.length > 3) {
        batchName.value = data[0].name + '、' + data[1].name + '、' + data[2].name + '等'+(data.length)+'人'
      } else if (data.length == 3) {
        batchName.value = data[0].name + '、' + data[1].name + '、' + data[2].name
      } else if (data.length == 2) {
        batchName.value = data[0].name + '、' + data[1].name
      } else {
        batchName.value = data[0].name
      }
    } else {
      isBatch.value = false
    }
    batchAssign.assign_user_ids = []
    data.forEach((item: any) => {
      batchAssign.assign_user_ids.push(item.id as never)
    })
  }

  const reset = () => {
    batchAssign.assign_user_ids = []
  }

  const search = () => {
    batchAssign.assign_user_ids = []
  }

  //全选
  const selectAll = (data: any) => {
    if (data.length > 0) {
      isBatch.value = true
      batchName.value = data[0].name + '、' + data[1].name + '、' + data[2].name + '等'+data.length+'人'
    } else {
      isBatch.value = false
    }
    isSelectAll.value = true
    batchAssign.assign_user_ids = []
    data.forEach((item: any) => {
      batchAssign.assign_user_ids.push(item.id as never)
    })
  }
  //批量修改角色
  const batchEdit = () => {
    if (!isBatch.value) {
      ElMessage({
        message: '请选择账号',
        type: 'error'
      })
      return
    }
    roleDialog.visible = true
  }
  //获取企业权限
  const handleCompany = (data: any) => {
    savePermission.data_premission_type = data
  }
  //获取数据权限
  const handleSub = (data: any) => {
    data == 4 ? (savePermission.data_permissions = '1') : data == 5 ? (savePermission.data_permissions = '2') : data == 6 ? (savePermission.data_permissions = '3') : (savePermission.data_permissions = data)
    permission.data_permissions = data
  }
  //获取选择的节点
  const handleSelect = (data: any) => {
    savePermission.application_function_id = data
  }
  watch(() => activeIndex.value, (val) => {
    if(val == '2') tableRef.value.getsubList(selectId.value)
  })
  onMounted(() => {
    account_type.value = localStorage.getItem('account_type')
  })
</script>
<style lang="scss" scoped>
  .content {
    display: flex;
    justify-content: center;
    .left-nav {
      width: 270px;
      border: 1px solid #eaeaea;
      background-color: #ffffff;
      padding: 16px;
      margin-right: 16px;
      .nav-title {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      .nav-text {
        font-size: 16px;
        font-weight: 600;
        color: #33302d;
      }
      .search-list {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 5px 0 5px 20px;
        .search-detail {
          color: #33302d;
        }
        .search-detail-color {
          color: #ff6b00;
        }
        .hover-icon {
          transform: rotate(90deg);
        }
      }
      .search-list:hover {
        color: #ff6b00;
        background-color: #f5f7fa;
      }
    }
    .right-content {
      width: calc(100% - 360px);
      border: 1px solid #eaeaea;
      background-color: #ffffff;
      padding: 16px;
      .title-btn {
        display: flex;
        justify-content: space-between;
        height: 40px;
        .btn-group {
          .edit-role {
            background-color: #ff6b00;
            color: #ffffff;
          }
        }
      }
      .el-menu-item:hover {
        background-color: #fffaf9;
      }
      .company-content {
        display: flex;
        .company-detail {
          width: 230px;
          margin-right: 20px;
          .company-title {
            font-weight: 600;
            margin: 16px 0 16px 16px;
          }
          .company-list {
            line-height: 50px;
            margin: 0 22px;
            .company-avatar {
              vertical-align: middle;
            }
          }
          .company-list:hover {
            background-color: #fffaf9;
          }
          border: 1px solid #eaeaea;
        }
        .company-role {
          width: 100%;
        }
      }
      .table-search {
        padding: 10px;
        display: flex;
        justify-content: space-between;
      }
    }
  }
  .add-role {
    display: flex;
    .role-label {
      width: 100px;
      line-height: 40px;
    }
    .role-tip {
      color: #ff6b00;
      line-height: 50px;
    }
  }
  .detail-color {
    color: #ffc69e;
  }
  .local-color {
    color: #c3c3c3;
  }
  .change-title {
    line-height: 35px;
    .change-title-color {
      color: #ff6b00;
    }
  }
  .tip-title {
    line-height: 35px;
  }
  .tips {
    line-height: 20px;
    color: #81d3f8;
    margin: 10px 0;
  }
  .message {
    font-size: 16px;
    margin-bottom: 10px;
  }
  .save-detail {
    display: flex;
    .save-select {
      width: 150px;
      margin-left: 30px;
    }
  }
  .save-text {
    line-height: 35px;
    .save-link {
      display: inline-block;
      color: #ff6b00;
      padding-left: 50px;
    }
  }
  .save-message {
    display: flex;
    line-height: 40px;
    margin-top: 15px;
    .save-input {
      width: 150px;
      margin-right: 10px;
    }
  }
  .icon-detail {
    line-height: 30px;
    display: flex;
    align-items: center;
    .icon {
      font-size: 25px;
      margin-right: 5px;
    }
  }
</style>
